#include <fstream>

#include "http_server.hpp"
#include "Usage.hpp"
#include "Util.hpp"

#define ROOT "./wwwroot"
#define HOMEPAGE "index.html"

void HandlerHttpRequest(int sock)
{
    char buffer[10240];
    ssize_t s = recv(sock, &buffer, sizeof(buffer) - 1, 0);
    if (s > 0)
    {
        buffer[s] = 0;
        // std::cout << buffer << std::endl;
    }

    // 对接收的消息进行剪裁
    // 以设置首页
    std::vector<std::string> vline;
    Util::cutString(buffer, "\n", &vline);

    // 获取第一行的分割后的字符串
    std::vector<std::string> vblock;
    Util::cutString(vline[0], " ", &vblock);

    // 获取访问的页面和首页
    std::string file = vblock[1];
    std::string target = ROOT;

    // 设置首页（如果客户访问的只是/
    if (file == "/")
        file += HOMEPAGE;
    target += file;

    // 发消息
    std::string content;
    std::ifstream in(target);
    while (in.is_open())
    {
        std::string line;
        while (std::getline(in, line))
        {
            content += line;
        }
        in.close();
    }

    std::string HttpResponse;
    if (content.empty())
    {
        //永久重定向
        HttpResponse = "HTTP/1.1 301 Moved Permanently\r\n";
        HttpResponse += "Location: http://43.143.141.145:8080/a/404.html\r\n";
    }
    else
    {
        HttpResponse = "HTTP/1.1 200 OK\r\n";
        HttpResponse += ("Content-Type: text/html\r\n"); 
        HttpResponse += ("Content-Length: " + std::to_string(content.size()) + "\r\n");
        HttpResponse += "Set-Cookie: 这是一个cookie\r\n";
    }
    HttpResponse += "\r\n";
    HttpResponse += content;
    //HttpResponse += "<html><p>hello it is me</p></html>";
    // std::cout << "####start################" << std::endl;
    // for (auto &iter : vblock)
    // {
    //     std::cout << "---" << iter << "\n"
    //               << std::endl;
    // }
    // std::cout << "#####end###############" << std::endl;
    send(sock,HttpResponse.c_str(),HttpResponse.size(),0);
}

int main(int args, char *argv[])
{
    if (args != 2)
    {
        Usage(argv[0]);
        exit(-1);
    }

    Http_server *hsr(new Http_server(atoi(argv[1]), HandlerHttpRequest));
    hsr->Start();
    return 0;
}